<?php
class PriceSaleOrderPublicBehavior extends Behavior {
	public function run(&$params){  
		$last_price	= $this->getLastPrice();
		$avg_price	= $this->getAvgPrice();
		foreach ((array)$params['detail'] as $k=>$v){
			if($k>0 && $v['product_id']){
				$info['sale_last_price_'.$params['currency_id']]	= floatval($last_price[$v['product_id'].'_'.$params['currency_id']]);
				$info['sale_avg_price_'.$params['currency_id']]		= floatval($avg_price[$v['product_id'].'_'.$params['currency_id']]);
				M('ProductPrice')->where('product_id='.intval($v['product_id']))->save($info);
			}
		}
	}
	
	
	/**
	 * 计算产品的最后一次销售价格
	 *
	 */
	protected  function getLastPrice() {
		$model	= M('Instock');
		$sql	= '
			SELECT detail.price,  detail.product_id, sale.currency_id
			FROM sale_order_detail as detail left join sale_order  as sale on detail.sale_order_id=sale.id
			WHERE 1 
			GROUP BY  detail.product_id, sale.currency_id
			order by  detail.sale_order_id
		';
		$list	= $model->query($sql);
		foreach ((array)$list as $k=>$v){
			$info[$v['product_id'].'_'.$v['currency_id']]	= $v['price']; 
		}
		return $info;
	}
	/**
	 * 计算产品的平均销售价格
	 *
	 */
	protected  function getAvgPrice() {
		$model	= M('Instock');
		$sql	= '
			select sum(detail.quantity*detail.capability*detail.dozen*detail.price)/sum(detail.quantity*detail.capability*detail.dozen) as price,detail.product_id,sale.currency_id
			from sale_order_detail as detail left join sale_order  as sale on detail.sale_order_id=sale.id
			where 1 group by detail.product_id,sale.currency_id
		';
		$list	= $model->query($sql);
		foreach ((array)$list as $k=>$v){
			$info[$v['product_id'].'_'.$v['currency_id']]	= $v['price']; 
		}
		return $info;
	}
}


